package com.neusoft.tmall.ums.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.neusoft.tmall.ums.entity.UmsAdmin;
import com.neusoft.tmall.ums.entity.UmsAdminExample;
import com.neusoft.tmall.ums.mapper.UmsAdminMapper;
import com.neusoft.tmall.ums.service.UmsAdminService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements UmsAdminService{

    @Override
    public long countByExample(UmsAdminExample example) {
        return baseMapper.countByExample(example);
    }
    @Override
    public int deleteByExample(UmsAdminExample example) {
        return baseMapper.deleteByExample(example);
    }
    @Override
    public List<UmsAdmin> selectByExample(UmsAdminExample example) {
        return baseMapper.selectByExample(example);
    }
    @Override
    public int updateByExampleSelective(UmsAdmin record,UmsAdminExample example) {
        return baseMapper.updateByExampleSelective(record,example);
    }
    @Override
    public int updateByExample(UmsAdmin record,UmsAdminExample example) {
        return baseMapper.updateByExample(record,example);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询username的用户
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsAdmin> list = baseMapper.selectByExample(example);
        if (list == null || list.size() == 0) {
            throw new UsernameNotFoundException("用户名账号不存在");
        }

        UmsAdmin bean = list.get(0);
        //角色设置

        //Security有一个默认实现了UserDetails接口的类叫做User
//        SimpleGrantedAuthority
        Collection<GrantedAuthority> authorities = Lists.newArrayList();
        GrantedAuthority auth = new SimpleGrantedAuthority("ROLE_" + "admin");
        authorities.add(auth);
        auth = new SimpleGrantedAuthority("ROLE_" + "hello");
        authorities.add(auth);

        return new org.springframework.security.core.userdetails.User(username, bean.getPassword(), authorities);
    }
}
